<script setup>
import { ref, watch, onMounted, onBeforeUnmount } from 'vue'
import NavBar from './components/NavBar.vue'
import axios from './plugins/axios'
import { setWatermark, clearWatermark } from './plugins/watermark'

const watermarkText = ref('')
const hasStorage = typeof window !== 'undefined'

if (hasStorage) {
  const cachedName = localStorage.getItem('username')
  const cachedEmail = localStorage.getItem('userEmail')
  if (cachedName || cachedEmail) {
    watermarkText.value = [cachedName, cachedEmail].filter(Boolean).join(' ')
  }
}

const buildWatermarkText = (user) => {
  if (!user) return ''
  const username = user.username || user.realname || user.phone || ''
  const email = user.email || ''
  const parts = [username, email].filter(Boolean)
  return parts.join(' ')
}

const persistWatermarkInfo = (username, email) => {
  if (!hasStorage) return
  if (username) {
    localStorage.setItem('username', username)
  } else {
    localStorage.removeItem('username')
  }
  if (email) {
    localStorage.setItem('userEmail', email)
  } else {
    localStorage.removeItem('userEmail')
  }
}

const fetchWatermarkContent = async () => {
  if (!hasStorage) return
  const userId = localStorage.getItem('userId')
  const token = localStorage.getItem('token')
  if (!userId || !token) {
    watermarkText.value = ''
    persistWatermarkInfo('', '')
    return
  }

  try {
    const response = await axios.get(`/user/${userId}`, { suppressErrorToast: true })
    const profile = response.data?.data
    const text = buildWatermarkText(profile)
    watermarkText.value = text
    persistWatermarkInfo(profile?.username || profile?.realname || '', profile?.email || '')
  } catch (error) {
    console.error('水印信息获取失败', error)
  }
}

const applyWatermark = (text) => {
  if (text) {
    setWatermark(text)
  } else {
    clearWatermark()
  }
}

const handleUserInfoUpdated = () => {
  fetchWatermarkContent()
}

const handleStorageChange = (event) => {
  if (['token', 'userId', 'username', 'userEmail'].includes(event.key)) {
    fetchWatermarkContent()
  }
}

onMounted(() => {
  fetchWatermarkContent()
  if (hasStorage) {
    window.addEventListener('user-info-updated', handleUserInfoUpdated)
    window.addEventListener('storage', handleStorageChange)
  }
})

onBeforeUnmount(() => {
  if (hasStorage) {
    window.removeEventListener('user-info-updated', handleUserInfoUpdated)
    window.removeEventListener('storage', handleStorageChange)
  }
})

watch(watermarkText, applyWatermark, { immediate: true })
</script>

<template>
  <NavBar />
  <div class="context">
    <router-view />
  </div>
  
</template>

<style scoped>
.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
  transition: filter 300ms;
}
.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vue:hover {
  filter: drop-shadow(0 0 2em #42b883aa);
}
.context{
    margin-top: 100px;
}
</style>
